package com.itheima.mp.controller;


import com.itheima.mp.domain.po.UserInfoInput;
import com.itheima.mp.service.IUserInfoInputService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-12-02
 */
@RestController
@RequestMapping("/user-info-input")
public class UserInfoInputController {
    @Autowired
    private IUserInfoInputService userInfoInputService;

    // GET请求：获取所有用户信息
    @GetMapping("/list")
    public List<UserInfoInput> getAllUsers() {
        return userInfoInputService.list();
    }

    // GET请求：根据ID获取用户信息
    @GetMapping("/{id}")
    public UserInfoInput getUserById(@PathVariable String id) {
        return userInfoInputService.getById(id);
    }

    // POST请求：添加用户信息
    @PostMapping("/add")
    public boolean addUser(@RequestBody UserInfoInput userInfoInput) {
        if (userInfoInput.getId() == null) {
            // 生成自定义ID
            String customId = generateCustomId();
            userInfoInput.setId(customId);
        }
        return userInfoInputService.save(userInfoInput);
    }
    private String generateCustomId() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentDateTime = dateFormat.format(new Date());
        Random random = new Random();
        int randomNum = random.nextInt(9999); // 生成4位随机数
        return currentDateTime + String.format("%04d", randomNum); // 确保随机数是4位
    }
    // POST请求：批量添加用户信息
    @PostMapping("/add/batch")
    public boolean addBatchUsers(@RequestBody List<UserInfoInput> userInfoInputs) {
        // 使用 Stream API 为列表中的每个用户生成自定义ID
        List<UserInfoInput> updatedUserInfoInputs = userInfoInputs.stream()
                .peek(userInfoInput -> {
                    if (userInfoInput.getId() == null) {
                        userInfoInput.setId(generateCustomId());
                    }
                })
                .collect(Collectors.toList());

        return userInfoInputService.saveBatch(updatedUserInfoInputs);
    }
}
